<?php
/**
 * Created by PhpStorm.
 * User: Monkey
 * Date: 2021/10/13
 * Time: 11:27
 * Desc: 提现记录
 */
declare (strict_types=1);

namespace app\api\controller;

use app\api\base\controller\Base;
use app\api\validate\WithdrawValidate;
use app\extend\model\User;
use think\facade\Db;

class Withdraw extends Base
{
    /**
     * 列表
     */
    public function getList()
    {
        $validate = new WithdrawValidate();
        $ret = $validate->scene('getList')->check(input());
        if(!$ret){
            return json(_E($validate->getError()));
        }

        $page = input('page/d',1);
        $limit = input('limit/d',20);

        $where = [
            ['uid','=',self::$UserInfo['id']]
        ];

        $list = [];
        $count = \app\extend\model\Withdraw::where($where)->count();
        if($count > 0){
            $list = \app\extend\model\Withdraw::where($where)->order(['id' => 'desc'])->page($page)->limit($limit)->select();
        }

        return json([
            'code' => 0,
            'msg' => '获取成功',
            'count' => $count,
            'data' => $list,
        ])->send();
    }

    /**
     * 提现
     */
    public function withdraw()
    {
        if (request()->isPost()) {
            $validate = new WithdrawValidate();
            $ret = $validate->scene('withdraw')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $money = input('money', 0);
            $password = input('password', '');
            $type = input('type','');

            $userInfo = User::where([
                ['id','=',self::$UserInfo['id']]
            ])->field('id,pay_password,pay_salt,balance,status')->find();

            if($userInfo['status'] != 0){
                return json(_E('抱歉！您暂时无权出金'));
            }

            if($userInfo->pay_password != password($password, $userInfo->pay_salt)){
                return json(_E('支付密码错误'));
            }

            if($userInfo->balance < $money){
                return json(_E('提现金额大于余额'));
            }

            //获取网站配置
            $websiteConfigInfo = \app\extend\model\WebsiteConfig::where([
                ['id','=',1]
            ])->find();

            if($websiteConfigInfo->withdraw_min_money > $money){
                return json(_E('单笔最低提现金额为：'.$websiteConfigInfo->withdraw_min_money));
            }
            if($websiteConfigInfo->withdraw_max_money < $money){
                return json(_E('单笔最高提现金额为：'.$websiteConfigInfo->withdraw_max_money));
            }

            $withdrawCount = \app\extend\model\Withdraw::where([
                ['uid','=',self::$UserInfo['id']],
                ['created_at','between',[date('Y-m-d'),date('Y-m-d 23:59:59')]]
            ])->count();

            if($withdrawCount >= $websiteConfigInfo['withdraw_num']){
                return json(_E('每日最多提现次数为：'.$websiteConfigInfo['withdraw_num']));
            }

            $timeArr = explode(',',$websiteConfigInfo->withdraw_time);

            //判断提现时间
            if(date('H') < $timeArr[0] || date('H') > $timeArr[1]){
                return json(_E('出金时间为：'.$timeArr[0].'~'.$timeArr[1]));
            }

            try {
                // 启动事务
                Db::startTrans();

                User::where([
                    ['id','=',self::$UserInfo['id']]
                ])->update([
                    'balance' => $userInfo->balance - $money,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

                //判断是否扣除提现手续费
                $price = $money;
                if($websiteConfigInfo->withdraw_fee > 0){
                    $price -= ($money * $websiteConfigInfo->withdraw_fee / 100);
                }

                \app\extend\model\Withdraw::insert([
                    'uid' => self::$UserInfo['id'],
                    'money' => $price,
                    'origin_money' => $money,
                    'withdraw_fee' => $websiteConfigInfo->withdraw_fee,
                    'balance' => $userInfo->balance - $money,
                    'type' => $type,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

                Db::commit();
                return json(_S('提现申请成功，等待审批'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(_E('提现申请失败'));
            }
        }
    }
}
